﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ForumServer;
using ForumLibrary;
using ForumLibrary.Data;

namespace ForumGUI
{
    public partial class ForumsFrame : Form
    {
        private List<String> _forums;
        private ForumManager _manager;
        private ClientController _controller;

        public ForumsFrame(ref ClientController controller, ref ForumManager manager)
        {
            InitializeComponent();
            _controller = controller;
            _controller.pushForm(this);
            _manager = manager;
            string forumsList = "";
            try
            {
                forumsList = (string)_manager.getForums();
            }
            catch (Exception)
            {
                MessageBox.Show("Server is down. Please Logout and try again in a few minutes");
            }
            ForumList.Text = "";
            char[] delimiter = { '\n' };
            String[] headers = forumsList.Split(delimiter);
            _forums = new List<string>();
            foreach (string s in headers)
            {
                if (!String.IsNullOrEmpty(s))
                {
                    _forums.Add(s);
                    ForumList.Items.Add(s);
                }
            }
        }

        private void ForumsFrame_Load(object sender, EventArgs e)
        {

        }

        private void Title_Click(object sender, EventArgs e)
        {

        }

        private void selectForum_Click(object sender, EventArgs e)
        {
            if (ForumList.SelectedIndex < 0 || ForumList.SelectedIndex > ForumList.Items.Count - 1)
            {
                MessageBox.Show("Please select forum!!!");
                return;
            }
            this.Visible = false;
            new ThreadsFrame(_controller, ref _manager, _forums.ElementAt(ForumList.SelectedIndex)).Visible  = true;
        }

        private void ReturnButton_Click(object sender, EventArgs e)
        {
            /*Form lastForm = _controller.popForm();
            if (lastForm != null)
            {
                lastForm.Visible = true;
                this.Dispose(false);
            }*/
            _manager.logout(_controller.Username);
            this.Dispose(false);
            LoginFrame l = new LoginFrame(ref _manager);
            l.Visible = true;
        }

        private void editFriendsButton_Click(object sender, EventArgs e)
        {
            ProfileFrame p = new ProfileFrame(ref _manager, ref _controller, _controller.Username);   
            p.Visible = true;
            this.Visible = false;
        }

        private void ForumList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.selectForum_Click(null, null);
        }
    }
}
